package com.juicygames.framework.draw.sprite;

import android.content.Context;
import android.util.Log;

import com.juicygames.framework.action.DrawAction;
import com.juicygames.framework.draw.ContextProperty;
import com.juicygames.framework.handler.DrawHandler;
import com.juicygames.framework.property.IsVisible;
import com.juicygames.framework.property.space.Position;
import com.juicygames.shmup.world.World;

public class SpriteDrawer extends DrawHandler {
	private static final String LOGTAG = SpriteDrawer.class.getName();

	private Animation currentAnimation;
	private AnimationGroup animationGroup;
	
	private Position position;
	private IsVisible isVisible;
	
	public SpriteDrawer(Animation animation) {
		super();
		this.currentAnimation = animation;
		animationGroup = new AnimationGroup();
		animationGroup.add(animation);
	}
	
	public SpriteDrawer(Animation[] animations) {
		assert(animations.length > 0);

		animationGroup = new AnimationGroup();
		for (Animation animation : animations) {
			animationGroup.add(animation);
		}
		
		currentAnimation = animations[0];
	}
		
	public void load() {
		Context context = getWorld().getPart(ContextProperty.class).get();
		
		for (Animation animation : animationGroup.values()) {
			animation.load(context.getResources());
		}
		
		position = parent.getPart(Position.class);
		isVisible = parent.tryToGetPart(IsVisible.class);
	}
	
	public void setAnimation(Class<? extends Animation> animationClass) {
		currentAnimation = animationGroup.get(animationClass);
		currentAnimation.reset();
	}
	
	public void handle(DrawAction draw) {
		if (isVisible == null || isVisible.get()) {
			float leftCornerCoord = position.get().x - currentAnimation.getWidth()/2;
			float topCornerCoord = position.get().y - currentAnimation.getHeight()/2;
			
			currentAnimation.draw(draw.getCanvas(), leftCornerCoord, topCornerCoord);
		}
		currentAnimation.stepFrame();
	}
	

}
